import { ref } from 'vue'

export function useExportChart(svgRef) {
    const exporting = ref(false)

    const exportChart = async () => {
        if (!svgRef.value || exporting.value) return
        exporting.value = true

        try {
            const svg = svgRef.value
            const zoomGroup = svg.querySelector('.zoom-group')
            const originalImages = Array.from(zoomGroup.querySelectorAll('image'))
            const imagePromises = originalImages.map(img =>
                fetch(img.getAttribute('href'))
                    .then(res => res.blob())
                    .then(blob => new Promise((resolve) => {
                        const reader = new FileReader()
                        reader.onload = () => resolve(reader.result)
                        reader.readAsDataURL(blob)
                    }))
            )

            // 等待所有图片加载
            const imageDataUrls = await Promise.all(imagePromises)

            const clonedSvg = svg.cloneNode(true)
            const clonedImages = clonedSvg.querySelectorAll('image')
            clonedImages.forEach((img, index) => {
                img.setAttribute('href', imageDataUrls[index])
            })

            const bbox = zoomGroup.getBBox()
            const padding = 50
            const width = Math.ceil(bbox.width + padding * 2)
            const height = Math.ceil(bbox.height + padding * 2)

            clonedSvg.setAttribute('width', width)
            clonedSvg.setAttribute('height', height)
            clonedSvg.setAttribute('viewBox', `0 0 ${width} ${height}`)

            const clonedGroup = clonedSvg.querySelector('.zoom-group')
            clonedGroup.setAttribute('transform', `translate(${-bbox.x + padding}, ${-bbox.y + padding})`)

            const svgData = new XMLSerializer().serializeToString(clonedSvg)
            const canvas = document.createElement('canvas')
            const scale = 2
            canvas.width = width * scale
            canvas.height = height * scale

            const ctx = canvas.getContext('2d')
            ctx.scale(scale, scale)

            const img = new Image()
            img.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svgData)

            await new Promise((resolve, reject) => {
                img.onload = resolve
                img.onerror = reject
            })

            ctx.fillStyle = 'white'
            ctx.fillRect(0, 0, canvas.width, canvas.height)
            ctx.drawImage(img, 0, 0, width, height)

            const link = document.createElement('a')
            link.download = '树形图.png'
            link.href = canvas.toDataURL('image/png')
            link.click()

        } catch (error) {
            console.error('Export failed:', error)
        } finally {
            exporting.value = false
        }
    }

    return { exporting, exportChart }
}